package fy.uap.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import fy.mdm.dao.NewFindeDao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.ctp.util.UUIDLong;

import fy.config.FyConfig;
import fy.uap.bean.MergerProviderFormBean;
import fy.uap.bean.RangeBean;
import fy.util.DBUtil;
import fy.util.MyUtil;

public class MergerProviderFormDao {



    private static org.apache.commons.logging.Log log = LogFactory
            .getLog(MergerProviderFormDao.class);

    private final static String updateSuppliserBankInfo = "update fy_supplier_vendor_invclass i set i.bankaccountname=?,i.bankcode = ?, i.bank = ?,i.bankaccount = ?,i.currency = ? where i.pk_vendor = ( select v.pk_vendor from fy_supplier_vendor v where v.cvencode = ? and nvl(v.dr,0) = 0)";

    private final static String updateSuppliserVendor = "update fy_supplier_vendor set cvenname=?,ctrade=?,cvenregcode=?,dorf=?,cqualitycond=?,cvenbank=?,cvenaccount=?,cmoneytype=?,cpurbillcode=?,couttype=?,cvenaddress=?,cvenpostcode=?, cvenperson=?, cvenphone=?,cvenfax=?,cvenemail=?,cveniaddress=?,ccuspaycond=?,ccontent=?,cycle=?,ccreateperson=?, ts=to_date(?, 'YYYY-MM-DD') , cvencode=?, cVenBankMemo=? where cvencode=? and (dr='0' or dr is null) ";

//    private final static String insertLog = "insert into fy_supplier_vendor_history(pk_venhis, pk_vendor, pk_corp, pk_invclass, changetype, changememo, changevouch, changecode, changer, ts, changedate, creater) values (?, ?, ?, ?, ?, ?, ?, ?, ?,to_date(?, 'YYYY-MM-DD') , ?, ? )";//substr(start_date,1,10)
    private final static String insertLog = "insert into fy_supplier_vendor_history(pk_venhis, pk_vendor, pk_corp, pk_invclass, changetype, changememo, changevouch, changecode, changer, ts, changedate, creater) values (?, ?, ?, ?, ?, ?, ?, ?, ?,to_date(substr(?,1,10), 'YYYY-MM-DD') , ?, ? )";//substr(start_date,1,10)
    
    private final static String findAllOldInClass = "select pk_veninv, trim(pk_corp), pk_invclass, cvendorclass, denddate, dvendevdate, dlastdate, pk_vendor from fy_supplier_vendor_invclass where pk_vendor=(select pk_vendor from  fy_supplier_vendor where cvencode = ?) and (dr='0' or dr is null) ";

    private final static String findFy_supplier_vendor = "select pk_vendor from fy_supplier_vendor where cvencode = ? and (dr='0' or dr is null)";

    private final static String stopOldInClass = "update fy_supplier_vendor_invclass set denddate = to_char( sysdate, 'yyyy-mm-dd') where pk_vendor=(select v.pk_vendor from  fy_supplier_vendor v where v.cvencode = ? and (v.dr='0' or v.dr is null)) and (dr='0' or dr is null) and denddate is null";

    private final static String stopSuppliserVendor = "update fy_supplier_vendor set denddate = to_char( sysdate, 'yyyy-mm-dd') where cvencode=? and (dr='0' or dr is null)";

    private final static String inserInClassIfNotExists = "insert into fy_supplier_vendor_invclass ( pk_veninv, pk_corp, pk_invclass, cvendorclass, denddate, dvendevdate, dlastdate, pk_vendor, creater ) select ?, ?, ?, ?, ?, ?, ?, ?, ?  from dual where not exists( select * from fy_supplier_vendor_invclass f where f.pk_vendor=(select pk_vendor from  fy_supplier_vendor where cvencode = ? and (dr='0' or dr is null)) and trim(f.pk_corp) = ? and f.pk_invclass=? and (f.dr='0' or f.dr is null))";

    private final static String uapUserID = "0001AA10000000009KX7";

/*    private static final String ERPUADATE = "update apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " av set (av.vendors_name, av.flag,av.zt,av.disable_date) = (select v.cvenname cvenname,      decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),   -1,   'N',   decode(vi.cvendorclass, '3', 'N', 'Y')) flag   ,decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',   decode(vi.cvendorclass,          '1',          '合格',          '2',          '潜在',          '3',          '黑名单',          vi.cvendorclass)) zt,      to_date(vi.denddate, 'YYYY-MM-DD') disable_date from fy_supplier_vendor_invclass vi left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor left join bd_corp c on vi.pk_corp = c.pk_corp left join fy_supplier_invclass i on vi.pk_invclass =       i.pk_invclass          where v.cvencode = ? and (vi.dr is null or vi.dr = 0) and av.vendors_num =v.cvencode and av.syb=c.unitname and av.uaplb = i.cinvclasscode )  where av.vendors_num =  ?";

    private static final String ERPUADATE_VENDORSNAME = "update apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " av set (av.vendors_name ) = (select v.CVENNAME from fy_supplier_vendor v where v.CVENCODE = ? AND (   v.dr IS NULL  OR v.dr = 0  ) )  where av.vendors_num =  ?";*/
    private static final String ERPUADATE = "update apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " av set (av.vendors_name, av.flag,av.zt,av.disable_date) = (select v.cvenname cvenname, (CASE WHEN vi.denddate is not null AND sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate) < 0 THEN 'N' ELSE decode(vi.cvendorclass,  '3',  'N',  'Y')  END ) flag ,decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',   decode(vi.cvendorclass,          '1',          '合格',          '2',          '潜在',          '3',          '黑名单',          vi.cvendorclass)) zt,      to_date(vi.denddate, 'YYYY-MM-DD') disable_date from fy_supplier_vendor_invclass vi left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor left join bd_corp c on vi.pk_corp = c.pk_corp left join fy_supplier_invclass i on vi.pk_invclass =       i.pk_invclass          where v.cvencode = ? and (vi.dr is null or vi.dr = 0) and av.vendors_num =v.cvencode and av.syb=c.unitname and av.uaplb = i.cinvclasscode )  where av.vendors_num =  ?";

    private static final String ERPUADATE_VENDORSNAME = "update apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " av set (av.vendors_name ) = (select v.CVENNAME from fy_supplier_vendor v where v.CVENCODE = ? AND (   v.dr IS NULL  OR v.dr = 0  ) )  where av.vendors_num =  ?";

//        public static final String ERP_MODIFY_PROVIDER_NAME = "update apps.FYG_PO_UAP_VENDORS@"
//			+ FyConfig.getERP_DB_CONFIG().getDblink() 
//			+ " av set av.vendors_name = ";
   /* private static final String ERPINSERTSQL = "insert into apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + "(VENDORS_NUM, VENDORS_NAME, SYB, UAPLB, ZT, disable_date,flag) select * from (select v.cvencode cvencode,  v.cvenname cvenname,  c.unitname unitname,  i.cinvclasscode cinvclasscode,  decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',decode(vi.cvendorclass,'1','合格',  '2',  '潜在',  '3',  '黑名单',  vi.cvendorclass)) zt,  to_date(vi.denddate, 'YYYY-MM-DD') disable_date,  decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'N',decode(vi.cvendorclass,  '3',  'N',  'Y')) flag   from fy_supplier_vendor_invclass vi    left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor    left join bd_corp c on vi.pk_corp = c.pk_corp    left join fy_supplier_invclass i on vi.pk_invclass = i.pk_invclass where v.cvencode=? and (vi.dr is null or vi.dr = 0) ) t where not exists ( select *    from apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " e where t.cvencode = e.VENDORS_NUM and e.SYB = t.unitname and e.UAPLB=t.cinvclasscode and t.zt = e.zt and (t.disable_date is null and e.disable_date is null or t.disable_date = e.disable_date) ) ";
*/
    private static final String ERPINSERTSQL = "insert into apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + "(VENDORS_NUM, VENDORS_NAME, SYB, UAPLB, ZT, disable_date,flag) select * from (select v.cvencode cvencode,  v.cvenname cvenname,  c.unitname unitname,  i.cinvclasscode cinvclasscode,  decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',decode(vi.cvendorclass,'1','合格',  '2',  '潜在',  '3',  '黑名单',  vi.cvendorclass)) zt,  to_date(vi.denddate, 'YYYY-MM-DD') disable_date,(CASE WHEN vi.denddate is not null AND sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate) < 0 THEN 'N' ELSE decode(vi.cvendorclass,  '3',  'N',  'Y') END ) flag   from fy_supplier_vendor_invclass vi    left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor    left join bd_corp c on vi.pk_corp = c.pk_corp    left join fy_supplier_invclass i on vi.pk_invclass = i.pk_invclass where v.cvencode=? and (vi.dr is null or vi.dr = 0) ) t where not exists ( select *    from apps.FYG_PO_UAP_VENDORS@"
            + FyConfig.getERP_DB_CONFIG().getDblink()
            + " e where t.cvencode = e.VENDORS_NUM and e.SYB = t.unitname and e.UAPLB=t.cinvclasscode and t.zt = e.zt and (t.disable_date is null and e.disable_date is null or t.disable_date = e.disable_date) ) ";
    private MergerProviderFormBean mergerProviderFormBean;

    private List<RangeBean> rangeList;

    private boolean writeToErpSuccess = false;

    private boolean writeAptitudeSuccess;

    public boolean isWriteToErpSuccess() {
        return writeToErpSuccess;
    }

    public void setMergerProviderFormBean(

            MergerProviderFormBean mergerProviderFormBean) {
        log.info("ERPUADATE_VENDORSNAME = "+ERPUADATE_VENDORSNAME);
        this.mergerProviderFormBean = mergerProviderFormBean;
    }

    public boolean save() {
        log.info("ERPUADATE_VENDORSNAME = "+ERPUADATE_VENDORSNAME);
        boolean success = false;
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.connect(FyConfig.getUAP_DB_CONFIG());

            if (mergerProviderFormBean.isChangeName()) {
                success = saveChangeNameForm(conn);
            } else {
                success = saveMergerForm(conn);
            }

            pst = conn.prepareStatement(updateSuppliserBankInfo);

            pst.setString(1, mergerProviderFormBean.getBankAccountName());
            pst.setString(2, mergerProviderFormBean.getBankCode());
            pst.setString(3, mergerProviderFormBean.getcVenBankMemo());
            pst.setString(4, mergerProviderFormBean.getBankAccount());
            pst.setString(5, mergerProviderFormBean.getCmoneytype());
            pst.setString(
                    6,
                    MyUtil.strIsNotNull(mergerProviderFormBean
                            .getNewProviderCode()) ? mergerProviderFormBean
                            .getNewProviderCode() : mergerProviderFormBean
                            .getOldProviderCode());
            DBUtil.close(pst);

            conn.commit();

            // 查询目标供应商编码对应的供应商信息
            pst = conn
                    .prepareStatement("select i.pk_corp, i.pk_invclass, c.unitname, si.cinvclasscode, v.cvencode, i.cvendorclass, v.cvenname, i.denddate from fy_supplier_vendor_invclass i left join bd_corp c on i.pk_corp = c.pk_corp left join fy_supplier_invclass si on si.pk_invclass = i.pk_invclass left join fy_supplier_vendor v on v.pk_vendor = i.pk_vendor where v.cvencode=? and (i.dr='0' or i.dr is null) and (i.denddate is null or to_date(i.denddate,'yyyy-mm-dd') > to_date( to_char(sysdate, 'yyyy-mm-dd'), 'yyyy-mm-dd' ))");
            pst.setString(1, mergerProviderFormBean.getNewProviderCode());
            rs = pst.executeQuery();
            while (rs.next()) {

                if (rangeList == null) {
                    rangeList = new ArrayList<RangeBean>();
                }
                rangeList
                        .add(new RangeBean(rs.getString(1), rs.getString(2), rs
                                        .getString(3), rs.getString(5),
                                        rs.getString(4), rs.getString(6), rs
                                        .getString(7), rs.getString(8)));
            }

            try {
                pst = conn
                        .prepareStatement("update apps.FYG_PO_UAP_VENDORS@"
                                + FyConfig.getERP_DB_CONFIG().getDblink()
                                + " f set f.flag = 'N' where f.vendors_num = ?  and f.ZT  NOT IN ('潜在','合格','99') ");

                pst.setString(1, mergerProviderFormBean.getOldProviderCode());

                pst.execute();
                DBUtil.close(pst);
                //log.info("mergerProviderFormBean.isChangeName()="+mergerProviderFormBean.isChangeName());
                if (mergerProviderFormBean.isChangeName()) {
                    pst = conn.prepareStatement(ERPUADATE_VENDORSNAME);
                    pst.setString(1, mergerProviderFormBean
                            .getOldProviderCode());
                    pst.setString(2, mergerProviderFormBean
                            .getOldProviderCode());
                    pst.execute();
                } else {
                    // ERP更新
                    pst = conn.prepareStatement(ERPUADATE);
                    pst.setString(
                            1,
                            MyUtil.strIsNotNull(mergerProviderFormBean
                                    .getNewProviderCode()) ? mergerProviderFormBean
                                    .getNewProviderCode() : mergerProviderFormBean
                                    .getOldProviderCode());
                    pst.setString(
                            2,
                            MyUtil.strIsNotNull(mergerProviderFormBean
                                    .getNewProviderCode()) ? mergerProviderFormBean
                                    .getNewProviderCode() : mergerProviderFormBean
                                    .getOldProviderCode());
                    pst.execute();

                    // ERP插入
                    pst = conn.prepareStatement(ERPINSERTSQL);
                    pst.setString(
                            1,
                            MyUtil.strIsNotNull(mergerProviderFormBean
                                    .getNewProviderCode()) ? mergerProviderFormBean
                                    .getNewProviderCode() : mergerProviderFormBean
                                    .getOldProviderCode());
                    pst.execute();
                }
                conn.commit();

                writeToErpSuccess = true;
            } catch (Exception e) {
                DBUtil.rollback(conn);
                DBUtil.setAutoCommit(conn, true);
                e.printStackTrace();

                log.error(
                        "供应商更名/合并写入ERP数据库异常,单据编号： "
                        + mergerProviderFormBean.getNumber(), e);
                writeToErpSuccess = false;
            }
        } catch (Exception e) {
            success = false;
            DBUtil.rollback(conn);
            e.printStackTrace();
            log.error("供应商更名/合并审批数据导入UPA异常", e);
        } finally {
            DBUtil.setAutoCommit(conn, true);
            DBUtil.close(rs, pst, conn);
        }
        // if (success)
        // writeToErp();

        return success;
    }

    /**
     * 当合并时
     *
     * @param conn
     * @return
     * @throws Exception
     */
    private boolean saveMergerForm(Connection conn) throws Exception {
        log.info("ERPUADATE_VENDORSNAME = "+ERPUADATE_VENDORSNAME);
        PreparedStatement pst = null;
        ResultSet rs = null;
        boolean success = false;

        try {

            pst = conn.prepareStatement(findFy_supplier_vendor);
            pst.setString(1, mergerProviderFormBean.getNewProviderCode());
            rs = pst.executeQuery();
            String newPk_vendor = null;
            if (rs.next()) {
                newPk_vendor = rs.getString(1);
            }
            DBUtil.close(rs, pst);
            if (newPk_vendor != null) {

                pst = conn.prepareStatement(findAllOldInClass);

                pst.setString(1, mergerProviderFormBean.getOldProviderCode());

                rs = pst.executeQuery();

                List<SupplyTypeBean> invclassList = new ArrayList<MergerProviderFormDao.SupplyTypeBean>();
                while (rs.next()) {
                    SupplyTypeBean bean = new SupplyTypeBean();
                    bean.setPk_veninv(String
                            .valueOf(UUIDLong
                                    .longUUID()));
                    bean.setPk_corp(rs.getString("trim(pk_corp)"));
                    bean.setPk_invclass(rs.getString("pk_invclass"));
                    bean.setCvendorclass(rs.getString("cvendorclass"));
                    bean.setDenddate(rs.getString("denddate"));
                    bean.setDvendevdate(rs.getString("dvendevdate"));
                    bean.setDlastdate(rs.getString("dlastdate"));
                    bean.setPk_vendor(newPk_vendor);

                    invclassList.add(bean);
                }
                DBUtil.close(rs, pst);

                conn.setAutoCommit(false);

                pst = conn.prepareStatement(updateSuppliserVendor);

                pst.setString(1, mergerProviderFormBean.getNewProviderName());
                pst.setString(2, mergerProviderFormBean.getCompanyType());
                pst.setString(3, mergerProviderFormBean.getTaxRegister());
                pst.setString(4, mergerProviderFormBean.getProperty());
                pst.setString(5, mergerProviderFormBean.getQualitySystem());
                pst.setString(6, mergerProviderFormBean.getCvenbank());
                pst.setString(7, mergerProviderFormBean.getBankAccount());
                pst.setString(8, mergerProviderFormBean.getCmoneytype());
                pst.setString(9, mergerProviderFormBean.getCpurbillcode());
                pst.setString(10, mergerProviderFormBean.getCouttype());
                pst.setString(11, mergerProviderFormBean.getSupplyAddress());
                pst.setString(12, mergerProviderFormBean.getPostCode());
                pst.setString(13, mergerProviderFormBean.getLinkman());
                pst.setString(14, mergerProviderFormBean.getTel());
                pst.setString(15, mergerProviderFormBean.getFax());
                pst.setString(16, mergerProviderFormBean.getEmail());
                pst.setString(17, mergerProviderFormBean.getAddress());
                pst.setString(18, mergerProviderFormBean.getCcuspaycond());
                pst.setString(19, mergerProviderFormBean.getCcontent());
                pst.setString(20, MyUtil.getLimitLengthString(
                        mergerProviderFormBean.getSupplyCycle(), 20, "…"));
                pst.setString(21, uapUserID);
                // pst.setString(22,
                // mergerProviderFormBean.getApplicationDate());
                pst.setString(22, mergerProviderFormBean.getApplicationDate());

                pst.setString(23, mergerProviderFormBean.getNewProviderCode());
                pst.setString(24, mergerProviderFormBean.getcVenBankMemo());

//				pst.setString(25, mergerProviderFormBean.getQylb());
//				pst.setString(26, mergerProviderFormBean.getZczj());
//				pst.setString(27, mergerProviderFormBean.getClsj());
//				pst.setString(28, mergerProviderFormBean.getNxse());
//				pst.setString(29, mergerProviderFormBean.getZgrs());
//				pst.setString(30, mergerProviderFormBean.getJycs());
//				pst.setString(31, mergerProviderFormBean.getFrdb());
//				pst.setString(32, mergerProviderFormBean.getFrdbsfz());
                pst.setString(25, mergerProviderFormBean.getNewProviderCode());

                pst.executeUpdate();

                DBUtil.close(pst);

                if (invclassList.size() > 0) {
                    // "insert into fy_supplier_vendor_invclass
                    // ( pk_veninv, pk_corp, pk_invclass, cvendorclass,
                    // denddate,
                    // dvendevdate, dlastdate, pk_vendor ) select ?, ?, ?, ?, ?,
                    // ?,
                    // ?, ?
                    // from dual where not exists( select * from
                    // fy_supplier_vendor_invclass f where f.pk_vendor=(select
                    // pk_vendor
                    // from fy_supplier_vendor where cvencode = ?) and
                    // trim(f.pk_corp) =
                    // ?)";

                    pst = conn.prepareStatement(inserInClassIfNotExists);

                    for (int i = 0, size = invclassList.size(); i < size; i++) {
                        SupplyTypeBean bean = invclassList.get(i);
                        pst.setString(1, bean.getPk_veninv());
                        pst.setString(2, bean.getPk_corp());
                        pst.setString(3, bean.getPk_invclass());
                        pst.setString(4,
                                "3".equals(bean.getCvendorclass()) ? "3" : "2");
                        pst.setString(5, bean.getDenddate());
                        pst.setString(6, bean.getDvendevdate());
                        pst.setString(7, bean.getDlastdate());
                        pst.setString(8, bean.getPk_vendor());
                        pst.setString(9, mergerProviderFormBean.getMemberCode());
                        pst.setString(10,
                                mergerProviderFormBean.getNewProviderCode());
                        pst.setString(11, bean.getPk_corp());
                        pst.setString(12, bean.getPk_invclass());
                        pst.addBatch();
                    }

                    pst.executeBatch();

                    DBUtil.close(pst);

                    pst = conn.prepareStatement(insertLog);
                    String note = new StringBuilder()
                            .append("供应商【")
                            .append(mergerProviderFormBean.getOldProviderName())
                            .append("】合并到【")
                            .append(mergerProviderFormBean.getNewProviderName())
                            .append("】;变更原因：")
                            .append(mergerProviderFormBean.getReason())
                            .toString();
                    for (int i = 0, size = invclassList.size(); i < size; i++) {
                        SupplyTypeBean bean = invclassList.get(i);
                        pst.setString(1, String
                                .valueOf(UUIDLong
                                        .longUUID()));
                        pst.setString(2, bean.getPk_vendor());
                        pst.setString(3, bean.getPk_corp());
                        pst.setString(4, bean.getPk_invclass());
                        pst.setString(5, "合并");
                        pst.setString(6, note);
                        pst.setString(7, "OA供应商更名/合并批准表");
                        pst.setString(8,
                                this.mergerProviderFormBean.getNumber());
                        pst.setString(9, uapUserID);
                        pst.setString(10, MyUtil.getNowStr());
                        pst.setString(11, MyUtil.getTodayDateStr());
                        pst.setString(12,
                                mergerProviderFormBean.getMemberCode());

                        pst.addBatch();
                    }

                    pst.executeBatch();

                    DBUtil.close(pst);

                    // 停用
                    pst = conn.prepareStatement(stopOldInClass);

                    pst.setString(1,
                            mergerProviderFormBean.getOldProviderCode());
                    // pst.setString(2, mergerProviderFormBean.getCompany());

                    pst.executeUpdate();

                    DBUtil.close(pst);

                    pst = conn.prepareStatement(stopSuppliserVendor);
                    pst.setString(1,
                            mergerProviderFormBean.getOldProviderCode());
                    pst.executeUpdate();

                    DBUtil.close(pst);

                    conn.commit();

                    writeAptitudeSuccess = true;
//					AptitudeDao.writeAptitude(conn,
//							apptitudeBeans,
//							mergerProviderFormBean.getNewProviderCode(), "合并"
//									+ mergerProviderFormBean.getNumber(),
//							mergerProviderFormBean.getMemberCode());

                    success = true;
                } else {
                    log.error("供应商更名/合并审批数据导入UPA异常:无法找到原供应商的供货范围，原供应商编码：:"
                            + mergerProviderFormBean.getOldProviderCode());
                }
            } else {
                log.error("供应商更名/合并审批数据导入UPA异常:无法找到目标供应商:"
                        + mergerProviderFormBean.getNewProviderCode());
            }
        } finally {
            DBUtil.close(rs);
            DBUtil.close(pst);
        }

        return success;
    }

    private void writeLog(Connection conn, String pk_vendor, String operate)
            throws SQLException {
        PreparedStatement pst = null;
        try {

            pst = conn.prepareStatement(insertLog);

            pst.setString(1, String
                    .valueOf(UUIDLong.longUUID()));
            pst.setString(2, pk_vendor);
            pst.setString(3, mergerProviderFormBean.getCompany());
            pst.setString(4, "");
            pst.setString(5, operate);
            pst.setString(
                    6,
                    new StringBuilder()
                    .append("原供应商【")
                    .append(mergerProviderFormBean.getOldProviderName())
                    .append("】更名为【")
                    .append(mergerProviderFormBean.getNewProviderName())
                    .append("】;变更原因：")
                    .append(mergerProviderFormBean.getReason())
                    .toString());
            pst.setString(7, "OA供应商更名/合并批准表");
            pst.setString(8, this.mergerProviderFormBean.getNumber());
            pst.setString(9, uapUserID);
            pst.setString(10, MyUtil.getNowStr());
//            System.err.println("时间"+MyUtil.getNowStr());
            pst.setString(11, MyUtil.getTodayDateStr());
            pst.setString(12, mergerProviderFormBean.getMemberCode());

            pst.executeUpdate();

        } finally {
            DBUtil.close(pst);
        }
    }

    /**
     * 当更名时
     *
     * @param conn
     * @return
     * @throws Exception
     */
    private boolean saveChangeNameForm(Connection conn) throws Exception {
        log.info("ERPUADATE_VENDORSNAME = "+ERPUADATE_VENDORSNAME);
        PreparedStatement pst = null;
        ResultSet rs = null;
        boolean success = false;
        try {
            conn.setAutoCommit(false);

            pst = conn.prepareStatement(updateSuppliserVendor);

            pst.setString(1, mergerProviderFormBean.getNewProviderName());
            pst.setString(2, mergerProviderFormBean.getCompanyType());
            pst.setString(3, mergerProviderFormBean.getTaxRegister());
            pst.setString(4, mergerProviderFormBean.getProperty());
            pst.setString(5, mergerProviderFormBean.getQualitySystem());
            pst.setString(6, mergerProviderFormBean.getCvenbank());
            pst.setString(7, mergerProviderFormBean.getBankAccount());
            pst.setString(8, mergerProviderFormBean.getCmoneytype());
            pst.setString(9, mergerProviderFormBean.getCpurbillcode());
            pst.setString(10, mergerProviderFormBean.getCouttype());
            pst.setString(11, mergerProviderFormBean.getSupplyAddress());
            pst.setString(12, mergerProviderFormBean.getPostCode());
            pst.setString(13, mergerProviderFormBean.getLinkman());
            pst.setString(14, mergerProviderFormBean.getTel());
            pst.setString(15, mergerProviderFormBean.getFax());
            pst.setString(16, mergerProviderFormBean.getEmail());
            pst.setString(17, mergerProviderFormBean.getAddress());
            pst.setString(18, mergerProviderFormBean.getCcuspaycond());
            pst.setString(19, mergerProviderFormBean.getCcontent());
            pst.setString(
                    20,
                    MyUtil.getLimitLengthString(
                            mergerProviderFormBean.getSupplyCycle(), 20, "…"));
            pst.setString(21, uapUserID);
            // pst.setString(22, mergerProviderFormBean.getApplicationDate());
            pst.setString(22, mergerProviderFormBean.getApplicationDate());

            pst.setString(
                    23,
                    (mergerProviderFormBean.getNewProviderCode() == null
                    || "".equals(mergerProviderFormBean
                            .getNewProviderCode()) ? mergerProviderFormBean
                            .getOldProviderCode() : mergerProviderFormBean
                            .getNewProviderCode()));
            pst.setString(24, mergerProviderFormBean.getcVenBankMemo());

//			pst.setString(25, mergerProviderFormBean.getQylb());
//			pst.setString(26, mergerProviderFormBean.getZczj());
//			pst.setString(27, mergerProviderFormBean.getClsj());
//			pst.setString(28, mergerProviderFormBean.getNxse());
//			pst.setString(29, mergerProviderFormBean.getZgrs());
//			pst.setString(30, mergerProviderFormBean.getJycs());
//			pst.setString(31, mergerProviderFormBean.getFrdb());
//			pst.setString(32, mergerProviderFormBean.getFrdbsfz());
            pst.setString(25, mergerProviderFormBean.getOldProviderCode());
            pst.executeUpdate();

            DBUtil.close(pst);

            pst = conn
                    .prepareStatement("select t.pk_vendor from fy_supplier_vendor t where t.cvencode= ?");

            pst.setString(1, this.mergerProviderFormBean.getNewProviderCode());

            rs = pst.executeQuery();

            String pk_vendor = null;

            if (rs.next()) {
                pk_vendor = rs.getString(1);
            }

            DBUtil.close(pst);

            writeLog(conn, pk_vendor, "更名");

            conn.commit();

            writeAptitudeSuccess = true;
//			AptitudeDao.writeAptitude(conn,
//					apptitudeBeans,
//					mergerProviderFormBean.getNewProviderCode(), "更名"
//							+ mergerProviderFormBean.getNumber(),
//					mergerProviderFormBean.getMemberCode());

            success = true;
        } finally {
            DBUtil.close(rs);
            DBUtil.close(pst);
        }

        return success;
    }

    public boolean isWriteAptitudeSuccess() {
        return writeAptitudeSuccess;
    }

    private class SupplyTypeBean {

        private String pk_veninv;
        private String pk_corp;
        private String pk_invclass;
        private String cvendorclass;
        private String denddate;
        private String dvendevdate;
        private String dlastdate;
        private String pk_vendor;

        public String getPk_veninv() {
            return pk_veninv;
        }

        public void setPk_veninv(String pk_veninv) {
            this.pk_veninv = pk_veninv;
        }

        public String getPk_corp() {
            return pk_corp;
        }

        public void setPk_corp(String pk_corp) {
            this.pk_corp = pk_corp;
        }

        public String getPk_invclass() {
            return pk_invclass;
        }

        public void setPk_invclass(String pk_invclass) {
            this.pk_invclass = pk_invclass;
        }

        public String getCvendorclass() {
            return cvendorclass;
        }

        public void setCvendorclass(String cvendorclass) {
            this.cvendorclass = cvendorclass;
        }

        public String getDenddate() {
            return denddate;
        }

        public void setDenddate(String denddate) {
            this.denddate = denddate;
        }

        public String getDvendevdate() {
            return dvendevdate;
        }

        public void setDvendevdate(String dvendevdate) {
            this.dvendevdate = dvendevdate;
        }

        public String getDlastdate() {
            return dlastdate;
        }

        public void setDlastdate(String dlastdate) {
            this.dlastdate = dlastdate;
        }

        public String getPk_vendor() {
            return pk_vendor;
        }

        public void setPk_vendor(String pk_vendor) {
            this.pk_vendor = pk_vendor;
        }
    }
}
